#include "frmuserinfo.h"
#include "ui_frmuserinfo.h"

frmUserInfo::frmUserInfo(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::frmUserInfo)
{
    ui->setupUi(this);
    QImage image1;
    image1.load(":/img/userinfo.jpg");
    QImage image2=image1.scaled(400,300);

    QPalette palette;
    palette.setBrush(this->backgroundRole(),QBrush(image2));//设置背景
    setPalette(palette);
}

frmUserInfo::~frmUserInfo()
{
    delete ui;
}

void frmUserInfo::setId(int id)
{
    this->id = id;
    User *u = UserList::userlist->at(id);
    ui->letName->setText(QString::fromStdString(u->name));
    ui->letPassword->setText(QString::fromStdString(u->password));
}

void frmUserInfo::on_btnChange_clicked()
{
    if(id == 0)
    {
        QMessageBox::warning(this,"修改警告","体验账户不可被修改！");
        return;
    }
    string name = ui->letName->text().toStdString();
    string password = ui->letPassword->text().toStdString();
    if(QMessageBox::information(this,"确认修改","是否修改信息？",QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes)==QMessageBox::Yes){
        if(UserList::userlist->at(id)->name != name){
            if(judge(name, password))
                UserList::userlist->at(id)->name = name;
                UserList::userlist->at(id)->password = password;
                QMessageBox::warning(this,"提示","修改成功！");
                setId(id);
                ul.save();
                return;
        }
        if(password == "")
        {
            QMessageBox::critical(this, "错误", "修改失败！密码为空！");
            return;
        }
        UserList::userlist->at(id)->name = name;
        UserList::userlist->at(id)->password = password;
        QMessageBox::warning(this,"提示","修改成功！");
        setId(id);
        ul.save();
    }

}

void frmUserInfo::on_btnDelete_clicked()
{
    if(id == 0)
    {
        QMessageBox::warning(this,"注销警告","体验账户不可被注销！");
        return;
    }
    if(QMessageBox::information(this,"确认注销","是否注销账户？\n注意：所有数据都将会被清除！",QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes)==QMessageBox::Yes){
        UserList::userlist->erase(UserList::userlist->begin() + id);
        QMessageBox::warning(this,"提示","注销成功！");
        id = -1;
        ul.save();
        this->close();     
    }
}
int frmUserInfo::getId()
{
    return id;
}

bool frmUserInfo::judge(string name, string password)
{
    if(name == "" || password == ""){
            QMessageBox::critical(this, "错误", "修改失败！\n可能原因:姓名或密码为空！");
            return false;
        }
        for(int i = 0; i < UserList::userlist->size(); i++){
            User *u = UserList::userlist->at(i);
            if(name == u->name){
                QMessageBox::critical(this, "错误", "修改失败！昵称已被使用！");
                return false;
            }
        }
        return true;
}
